﻿@{
    ViewBag.Title = "企业网盘";
}
<style>
    .managerole .manage-action,.managerole .filebar-modify,.managerole .filebar-recycling{
        display:none;
    }
    .mfs-container{
        display:inline-block;
    }
</style>
<div class="leftbar">
    <ul>
        <li class="active" t="all">全部文件</li>
        <li class="indent2" t="image">图片</li>
        <li class="indent2" t="document">文档</li>
        <li class="indent2" t="vedio">视频</li>
        <li class="indent2" t="music">音乐</li>
        @*<li t="del">回收站</li>*@
    </ul>
</div>
<div class="body-content managerole">
    <input type="hidden" id="folderId" value="0" />
    <input type="hidden" id="folderDeptId" value="0" />
    <div class="topsection">
        <div class="actionbar">
            <div class="btn-group manage-action" role="group" style="float:left;margin-right:10px;">
                <span class="btn btn-primary fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i><span>上传文件</span>
                    <input id="fileupload" type="file" name="files[]" class="fileinput" multiple />
                </span>
                <button type="button" id="btnCreateFolder"  data-loading-text="新建..."  class="btn btn-primary">新建文件夹</button>
            </div>
            <div class="btn-group  manage-action" role="group" id="checkbar" style="float:left;margin-right:10px;display:none;">
                <button type="button" id="btnDelete" class="btn btn-danger"><i class="fa fa-trash"></i>  删除</button>
            </div>
            <div class="searchinput">
                <input id="txtSearch" onkeypress="if(event.keyCode==13) search(this);" placeholder="搜索文件" />
                <span class="searchicon"><i class="fa fa-search"></i></span>
            </div>
            <div style="clear:both;"></div>
            <div id="progress" style="width:100%;height:2px;background-color:#F8F8F8;border-radius:2px;display:none;">
                <div class="progress-bar"></div>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div class="path">
            全部文件
        </div>
        <div class="list-header order-0 asc-0" orderby="FILENAME" asc="ASC">
            <table>
                <tr>
                    <td orderby="FILENAME">
                        <span id="headerDescription">文件名</span>
                        <span class="sorttype0">
                            <i class="fa fa-sort-up"></i>
                            <i class="fa fa-sort-down"></i>
                        </span>
                    </td>
                    <td style="width:150px" orderby="DEPTNAME">
                       部门
                    </td>
                    <td style="width:150px" orderby="SIZE">
                        大小
                        <span class="sorttype1">
                            <i class="fa fa-sort-up"></i>
                            <i class="fa fa-sort-down"></i>
                        </span>
                    </td>
                    <td style="width:150px" orderby="LASTUPDATEDATE">
                        修改日期
                        <span class="sorttype2">
                            <i class="fa fa-sort-up"></i>
                            <i class="fa fa-sort-down"></i>
                        </span>
                    </td>
                </tr>
            </table>
            <div style="clear:both;"></div>
        </div>
    </div>
    <div class="list-folder-file">
        <table id="filetable"></table>
    </div>
</div>
    <script type="text/x-jquery-tmpl" id="folderRowTpl">
        <tr class="folder-row" fid="${ID}" deptid="${DeptID}" >
            <td class="folder" fid="${ID}">
                <div class="fileicon dir-small"></div>
                <span class="filename">${Name}</span>
                <div class="modify-name">
                    <input type="text" class="form-control" fid="${ID}" f="folder" style="width:200px;display: inline-block;" value="${Name}" />
                    <span class="btn btn-primary reNameFolderAccept" fid="${ID}"><i class="fa fa-check"></i></span>
                    <span class="btn btn-danger reNameFolderCancel" fid="${ID}"><i class="fa fa-close"></i></span>
                </div>
                <div class="filebar" role="group" style="float:right;">
                    <a href="javascript:void(0);" t="folderModifyName" class="filebar-modify" fid="${ID}"><i class="fa fa-edit"></i>  重命名</a>
                    <a href="javascript:void(0);" t="folderRecycling"  class="filebar-recycling" fid="${ID}"><i class="fa fa-trash"></i>  删除</a>
                </div>
            </td>
            <td  style="width:150px">${(DEPTNAME?DEPTNAME:'--')}</td>
            <td  style="width:150px">-</td>
            <td  style="width:150px">${CreateDate}</td>
        </tr>
    </script>
    <script type="text/x-jquery-tmpl" id="folderRowsTpl">
        {{each(i,row) data}}
        {{tmpl(row) '#folderRowTpl'}}
        {{/each}}
    </script>
    <script type="text/x-jquery-tmpl" id="fileRowsTpl">
        {{each(i,row) data}}
        <tr class="file-row">
            <td class="file" fid="${row.ID}">
                <div class="fileicon ${fileicon(row.Ext)}"></div>
                <span class="filename">${row.FileName}</span>
                <div class="modify-name">
                    <input type="text" class="form-control" fid="${row.ID}" f="file" style="width:200px;display: inline-block;" value="${row.FileName}" />
                    <span class="btn btn-primary reNameFileAccept" fid="${row.ID}"><i class="fa fa-check"></i></span>
                    <span class="btn btn-danger reNameFileCancel" fid="${row.ID}"><i class="fa fa-close"></i></span>
                </div>
                <div class="filebar" role="group" style="float:right;">
                    <a href="${row.Path}" download="${row.FileName}"  t="fileDownload" fid="${row.ID}"><i class="fa fa-download"></i>  下载</a>
                    <a href="javascript:void(0);" t="fileModifyName" class="filebar-modify" fid="${row.ID}"><i class="fa fa-edit"></i>  重命名</a>
                    <a href="javascript:void(0);" t="fileRecycling" class="filebar-recycling" fid="${row.ID}"><i class="fa fa-trash"></i>  删除</a>
                </div>
            </td>
            <td>--</td>
            <td style="width:150px">${conver(row.Size)}</td>
            <td style="width:150px">${row.LastUpdateDate}</td>
        </tr>
        {{/each}}
    </script>
    <script type="text/x-jquery-tmpl" id="nfolderTpl">
        <tr id="nfoldertr">
            <td class="nfolder" colspan="3">
                <span>名称:</span><input id="nfolder" type="text" class="form-control" style="width:200px;display: inline-block;" value="新建文件夹" />
                <span style="margin-left:10px;">部门:</span><input type="text" id="deptpicker" readonly="readonly" />
                <span class="btn btn-primary accept"><i class="fa fa-check"></i></span>
                <span class="btn btn-danger cancel"><i class="fa fa-close"></i></span>
            </td>
        </tr>
    </script>
    @section scripts{
        <script>
        $(function () {
            $(".searchicon").click(function () {
                search();
            });
            $(".leftbar ul li").click(function () {
                $(".leftbar ul li.active").removeClass("active");
                $(this).addClass("active");
                if ($(this).attr('t') == "all") {
                    $("#folderId").val("0");
                    $("#folderDeptId").val("0");
                } else {
                    $("#folderId").val("-1");
                    $("#folderDeptId").val("0");
                }
                $("#txtSearch").val("");
                $('#fileupload').fileupload('option', 'url', '/api/file/Upload?folderId=' + $("#folderId").val());
                createPath();
                queryFolders();
                queryFiles();
            });           
            $("#fileupload").fileupload({
                url: '/api/file/Upload?folderId=' + $("#folderId").val(),
                send: function (e, data) {
                    data.headers = {
                        Authorization: "basic " + $.cookie("token")
                    }
                },
                start: function (e, data) {
                    $("#progress").show();
                },
                done: function (e, data) {
                    if (data == null) {
                        toastr.warning(data.result.errmsg);
                    }
                    if (data.result.data != null) { }
                    $("#progress").hide();
                    toastr.info("上传成功");
                    queryFiles();
                },
                progressall: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $('#progress .progress-bar').css({ 'width': progress + '%' });
                }
            });
            $("#btnCreateFolder").click(function () {
                $("#btnCreateFolder").button('loading');
                _utility.ajax({
                    type: 'get',
                    url: '/api/Folder/GetFolderDeptChildren?id=' + $("#folderId").val(),
                    success: function (res) {
                        $("#nfolderTpl").tmpl({}, {}).prependTo($("#filetable"));
                        var items = [];
                        if (res.errcode == 0 && res.data.depts.length > 0) {                            
                            items = $.extend(true, [], res.data.depts);                            
                        }
                        if ($("#folderId").val() <= 0) {
                            items.push({ Name: '无', ID: 0, ParentID: -1 });
                        }
                        $(items).each(function () {
                            this['open'] = true;
                        });
                        $("#deptpicker").droptree('destroy');
                        $("#deptpicker").val(res.data.deptID);
                        $("#deptpicker").droptree({
                            idLabel: "ID",
                            textLabel: "Name",
                            pidLabel: "ParentID",
                            transition: "ztree",
                            items: items
                        });
                        $("#btnCreateFolder").button('reset');
                        $("#nfoldertr").find(".accept").click(function () {
                            var folderName = $.trim($("#nfolder").val());
                            if (folderName == '') {
                                toastr.warning("请输入文件夹名称");
                                return;
                            }
                            _utility.ajax({
                                url: '/api/folder/CreateFolder?folderId=' + $("#folderId").val() + '&folderName=' + folderName + '&deptID=' + $("#deptpicker").val(),
                                type: 'get',
                                success: function (res) {
                                    if (res.errcode == 0) {
                                        $("#deptpicker").droptree('destroy');
                                        $("#nfoldertr").remove();
                                        $("#folderRowTpl").tmpl(res.data, {}).prependTo($("#filetable"));
                                        bindFolderFunc();
                                    } else {
                                        toastr.warning(res.errmsg);
                                    }
                                }
                            });
                        });
                        $("#nfoldertr").find(".cancel").click(function () {
                            $("#deptpicker").droptree('destroy');
                            $("#nfoldertr").remove();
                        });
                    }
                });
                
            });         
            $("#btnDelete").click(function () {
                var files = [];
                var folders = [];
                $("input[type='checkbox'][t='file']:checked").each(function () {
                    files.push($(this).attr("fid"));
                });
                $("input[type='checkbox'][t='folder']:checked").each(function () {
                    folders.push($(this).attr("fid"));
                });
                if (files.length > 0) {
                    recyclingFiles(files, function (res) {
                        queryFiles();
                    });
                }
                if (folders.length > 0) {
                    recyclingFolders(folders, function (res) {
                        queryFolders();
                    });
                }
            });
            queryFolders();
            queryFiles();

            if (_utility.userInfo().Role == "Admin") {
                $(".managerole").removeClass('managerole');
            }
        });

        function search() {
            $(".leftbar ul li.active").removeClass("active");
            $(".leftbar ul li[t='all']").addClass("active");
            var search=$.trim($("#txtSearch").val());
            if (search != '') {
                var all = $("<a href='javascript:;' class='topath' fid='0'>全部文件</a>");
                var top = $("<a href='javascript:;' class='topath'  fid='0'>返回上一级</a>");
                $("#folderId").val("-1");
                $(".path").html('').append(top).append(" | ").append(all).append(" > ").append(" 搜索:" + $("#txtSearch").val());
            } else {
                $(".path").html('全部文件');
                $("#folderId").val("0");
            }
            $('#fileupload').fileupload('option', 'url', '/api/file/Upload?folderId=' + $("#folderId").val());
            createPath();
            queryFolders();
            queryFiles();
        }

        function createPath() {
            var t = $(".leftbar ul li.active").attr('t');
            var fid = $("#folderId").val();

            if(t == 'all'){
                if (fid == '0') {
                    $(".path").html('全部文件');
                } else if (fid == '-1') {
                    var search = $.trim($("#txtSearch").val());
                    if (search != '') {
                        var all = $("<a href='javascript:;' class='topath' fid='0' deptid='0'>全部文件</a>");
                        var top = $("<a href='javascript:;' class='topath'  fid='0' deptid='0'>返回上一级</a>");
                        $("#folderId").val("-1");
                        $(".path").html('').append(top).append(" | ").append(all).append(" > ").append(" 搜索:" + $("#txtSearch").val());
                        $(".topath").click(function () {
                            $("#txtSearch").val('');
                            $("#folderId").val($(this).attr("fid"));
                            $('#fileupload').fileupload('option', 'url', '/api/file/Upload?folderId=' + $("#folderId").val());
                            createPath()
                            queryFolders();
                            queryFiles();
                        });
                    } else {
                        $(".path").html('全部文件');
                    }
                } else {
                    _utility.ajax({
                        url: '/api/folder/getparent?id=' + fid,
                        success: function (res) {
                            var top = $("<a href='javascript:;' class='topath' fid='" + (res.data.length == 1 ? "0" : res.data[res.data.length - 2].ID) + "'>返回上一级</a>");
                            $(".path").html('').append(top).append(" | ").append("<a href='javascript:;' class='topath' fid='0'>全部文件</a>");
                            $(res.data).each(function (i) {
                                $(".path").append(" > ").append("<a href='javascript:;' class='topath'  fid='" + this.ID + "'>"+this.NAME+"</a>");
                            });
                            $(".topath").click(function () {
                                $("#txtSearch").val('');
                                $("#folderId").val($(this).attr("fid"));
                                $('#fileupload').fileupload('option', 'url', '/api/file/Upload?folderId=' + $("#folderId").val());
                                createPath()
                                queryFolders();
                                queryFiles();
                            });
                        }
                    });
                }
            } else if(t=='image'){
                $(".path").html('全部图片');
            } else if (t == 'document') {
                $(".path").html('全部文档');
            } else if (t == 'vedio') {
                $(".path").html('全部视频');
            } else if (t == 'music') {
                $(".path").html('全部音乐');
            } else if (t == 'del') {
                $(".path").html('回收站');
            }
        }

        function queryExts() {
            var t = $(".leftbar ul li.active").attr('t');
            if (t == 'image') {
                return ['.jpg','.gif','.png','.bmp'];
            } else if (t == 'document') {
                return ['.doc', '.docx', '.ppt', '.pptx','.txt','.xls','.xlsx'];
            } else if (t == 'vedio') {
                return ['.mp4', '.rmvb', '.mpeg', '.mov', '.mtv', '.wmv', '.avi', '.amv', '.3gp', '.dmv', '.flv'];
            } else if (t == 'music') {
                return ['.mp3', '.wav', '.wma'];
            }
            return [];
        }

        function queryState() {
            var t = $(".leftbar ul li.active").attr('t');
            return t == 'del'?0:1;
        }

        function queryFolders() {
            var orderby = $(".list-header").attr("orderby");
            var asc = $(".list-header").attr("asc");
            var folderId = $("#folderId").val();
            if (folderId == '-1') {
                $("#filetable").find(".folder-row").remove();
                return;
            }
            $.ajax({
                url: '/api/folder/GetFolderChildrens?folderId=' + folderId + "&orderby=" + orderby + "&asc=" + asc + "&search=" + $("#txtSearch").val()+"&state="+queryState(),
                type: 'get',
                beforeSend: function (req) {
                    req.setRequestHeader("Authorization", "basic " + $.cookie("token"));
                },
                success: function (res) {
                    if (res.errcode == 0) {
                        console.log(res.data);
                        $("#filetable").find(".folder-row").remove();
                        $("#folderRowsTpl").tmpl(res, {}).prependTo($("#filetable"));
                        bindFolderFunc();
                    }
                }
            });
        }

        function bindFolderFunc() {
            $("a[t='folderRecycling']").unbind('click').click(function () {
                var fileID = $(this).attr("fid");
                recyclingFolders([fileID], function (res) {
                    if (res.errcode == 0) {
                        $("td[fid='" + fileID + "']").parent().remove();
                    }
                });
            });

            $("a[t='folderModifyName']").unbind('click').click(function (event) {
                var folderID = $(this).attr("fid");
                $("td[fid='" + folderID + "']").addClass("modify");
                event.stopPropagation();
            });
            $(".reNameFolderCancel").unbind('click').click(function (event) {
                var folderID = $(this).attr("fid");
                $("td[fid='" + folderID + "']").removeClass("modify");
                event.stopPropagation();
            });

            $(".reNameFolderAccept").unbind('click').click(function (event) {
                var folderID = $(this).attr("fid");
                // fid="${ID}" f="folder"
                var folderName = $.trim($("input[type='text'][f='folder'][fid='" + folderID + "']").val());
                if (folderName == '') {
                    toastr.warning("请输入文件夹名称");
                    $("input[type='text'][t='folder'][fid='" + folderID + "']").focus();
                    return;
                }
                _utility.ajax({
                    url: '/api/Folder/ModifyFolderName?id=' + folderID + "&folderName=" + folderName,
                    type: 'get',
                    success: function (res) {
                        if (res.errcode == 0) {
                            $("input[type='text'][f='folder'][fid='" + folderID + "']").val(res.data.Name);
                            $("td[fid='" + folderID + "']").find(".filename").text(res.data.Name);
                            $("td[fid='" + folderID + "']").removeClass("modify");
                            toastr.info(res.errmsg);
                        } else {
                            toastr.warning(res.errmsg);
                        }
                    }
                });

                event.stopPropagation();
            });

            $(".folder-row").unbind('dblclick').dblclick(function () {
                var t = $(".leftbar ul li.active").attr('t');
                var fid = $.trim($(this).attr('fid'));

                if (t != 'del' && fid != '') {
                    $("#folderId").val(fid);
                    $('#fileupload').fileupload('option', 'url', '/api/file/Upload?folderId=' + $("#folderId").val());
                    createPath();
                    queryFolders();
                    queryFiles();
                }
            });
        }

        function queryFiles() {
            var orderby = $(".list-header").attr("orderby");
            var asc = $(".list-header").attr("asc");
            var folderId = $("#folderId").val();
            _utility.postJson({
                url: '/api/file/getfolderfiles?folderId=' + folderId + "&orderby=" + orderby + "&asc=" + asc + "&search=" + $("#txtSearch").val() + "&state=" + queryState(),
                data: JSON.stringify(queryExts()),
                success: function (res) {
                    if (res.errcode == 0) {
                        console.log(res.data);
                        $("#filetable").find(".file-row").remove();
                        $("#fileRowsTpl").tmpl(res, {}).appendTo($("#filetable"));
                        $("a[t='fileRecycling']").click(function () {
                            var fileID = $(this).attr("fid");
                            recyclingFiles([fileID],function(res){
                                if(res.errcode == 0){
                                    $("td[fid='" + fileID + "']").parent().remove();
                                }
                            });
                        });

                        $("a[t='fileModifyName']").click(function () {
                            var fileID = $(this).attr("fid");
                            $("td[fid='" + fileID + "']").addClass("modify");
                        });

                        $(".reNameFileCancel").click(function () {
                            var fileID = $(this).attr("fid");
                            $("td[fid='" + fileID + "']").removeClass("modify");
                        });

                        $(".reNameFileAccept").click(function () {
                            var fileID = $(this).attr("fid");
                            // fid="${ID}" f="folder"
                            var fileName = $.trim($("input[type='text'][f='file'][fid='" + fileID + "']").val());
                            if (fileName == '') {
                                toastr.warning("请输入文件名称");
                                $("input[type='text'][t='file'][fid='" + fileID + "']").focus();
                                return;
                            }
                            _utility.ajax({
                                url: '/api/File/ModifyFileName?id=' + fileID + "&fileName=" + fileName,
                                type:'get',
                                success:function(res){
                                    if(res.errcode == 0){
                                        $("input[type='text'][f='file'][fid='" + fileID + "']").val(res.data.FileName);
                                        $("td[fid='" + fileID + "']").find(".filename").text(res.data.FileName);
                                        $("td[fid='" + fileID + "']").removeClass("modify");
                                        toastr.info(res.errmsg);
                                    }else{
                                        toastr.warning(res.errmsg);
                                    }
                                }
                            });
                        });
                    }
                }
            });
        }

        function conver(limit) {
            var size = "";
            if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
                size = limit.toFixed(2) + "B";
            } else if (limit < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
                size = (limit / 1024).toFixed(2) + "KB";
            } else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
                size = (limit / (1024 * 1024)).toFixed(2) + "MB";
            } else { //其他转化成GB
                size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
            }

            var sizestr = size + "";
            var len = sizestr.indexOf("\.");
            var dec = sizestr.substr(len + 1, 2);
            if (dec == "00") {//当小数点后为00时 去掉小数部分
                return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
            }
            return sizestr;
        }

        function fileicon(ext) {
            var k = $.trim(ext + " ").toLowerCase();
            switch (k) {
                case ".jpg":
                case ".png":
                case ".bmp":
                case ".gif":
                    return "fileicon-small-pic";
                case ".torrent":
                    return "fileicon-small-bt";
                case ".dwg":
                case ".dws":
                case ".dwt":
                    return "fileicon-small-dws";
                case ".sql":
                case ".cs":
                case ".aspx":
                case ".html":
                    return "fileicon-small-code";
                case ".txt":
                    return "fileicon-small-txt";
                case ".pdf":
                    return "fileicon-small-pdf";
                case ".doc":
                case ".docx":
                    return "fileicon-small-doc";
                case ".ppt":
                case ".pptx":
                    return "fileicon-small-ppt";
                case ".xls":
                case ".xlsx":
                    return "fileicon-small-xls";
                case ".vsd":
                    return "fileicon-small-vsd";
                case ".mp3":
                    return "fileicon-small-mp3";
                case ".wav":
                case ".wma":
                    return "fileicon-small-music";
                case ".mp4":
                case ".rmvb":
                case ".mpeg":
                case ".mov":
                case ".mtv":
                case ".wmv":
                case ".avi":
                case ".3gp":
                case ".amv":
                case ".dmv":
                case ".flv":
                    return "fileicon-small-video";
                case ".apk":
                    return "fileicon-sys-s-apk";
                case ".exe":
                    return "fileicon-sys-s-exe";
                case ".psd":
                    return "fileicon-sys-s-psd";
                case ".ai":
                    return "fileicon-sys-s-ai";
            }

            return 'default-small';
        }

        function recyclingFiles(lstID,callback) {
            _utility.postJson({
                url: '/api/File/RecyclingFiles',
                data:JSON.stringify(lstID),
                success:function(res){
                    callback(res);
                }
            });
        }

        function recyclingFolders(lstID, callback) {
            _utility.postJson({
                url: '/api/Folder/RecyclingFolders',
                data: JSON.stringify(lstID),
                success: function (res) {
                    callback(res);
                }
            });
        }

        </script>
    }
